package com.software.levelupandroid.loginAndRegistration;

//import static com.software.levelupandroid.utils.JsonConverter.gson;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.software.levelupandroid.R;
import com.software.levelupandroid.entity.Result;
import com.software.levelupandroid.entity.User;
import com.software.levelupandroid.entity.UserCodeDTO;
import com.software.levelupandroid.home.HomeActivity;

import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ForgetActivity extends AppCompatActivity {
    private EditText new_password;
    private EditText confirm_password;
    private EditText name;
    private EditText verifyCode;
    private EditText email;
    private String responseContent,getCodeForUpdatePasswordServerPath,updatePasswordServerPath;
    private Gson gson;
    private Response response;
    private Result result;

    private String cookie;
    private Button btn_revise,forget_btn_verify;
    private OkHttpClient okHttpClient;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget);

        //初始化
        new_password = findViewById(R.id.forget_pwd);
        confirm_password = findViewById(R.id.forget_confirm_pwd);
        verifyCode = findViewById(R.id.forget_code);
        email = findViewById(R.id.forget_email);
        btn_revise = findViewById(R.id.btn_revise);
        forget_btn_verify = findViewById(R.id.forget_btn_verify);

        //初始化http客户端，并设置超时
        okHttpClient = new OkHttpClient()
                .newBuilder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60,TimeUnit.SECONDS)
                .build();
        gson = new Gson();


        //修改密码点击事件
        findViewById(R.id.btn_revise).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String new_pad = new_password.getText().toString();
                String con_pad =  confirm_password.getText().toString();
                String forget_email = email.getText().toString();
                String forget_code = verifyCode.getText().toString();

                if(TextUtils.isEmpty(new_pad)||TextUtils.isEmpty(con_pad)){
                    Toast.makeText(ForgetActivity.this, "密码不能为空", Toast.LENGTH_SHORT).show();
                } else if (!new_pad.equals(con_pad)) {
                    Toast.makeText(ForgetActivity.this, "新密码和确认密码不一致", Toast.LENGTH_SHORT).show();
                }
                else if((TextUtils.isEmpty(forget_email))){
                    Toast.makeText(ForgetActivity.this, "姓名或邮箱不能为空", Toast.LENGTH_SHORT).show();
                } else if (TextUtils.isEmpty(forget_code)) {
                    Toast.makeText(ForgetActivity.this, "验证码不能为空，请重新输入", Toast.LENGTH_SHORT).show();
                }else {
                    revise(new_pad,forget_email,forget_code);
                    Intent intent = new Intent(ForgetActivity.this, LoginActivity.class);
                    startActivity(intent);
                }
//                //跳转页面
//                Intent intent = new Intent(ForgetActivity.this, LoginActivity.class);
//                startActivity(intent);
            }
        });

        //发送验证码点击事件
        forget_btn_verify.findViewById(R.id.forget_btn_verify).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String forget_email = email.getText().toString();
                if (TextUtils.isEmpty(forget_email)) {
                    Toast.makeText(ForgetActivity.this, "邮箱不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    //倒计时
                    countCode();
                    sendVerificationCode(forget_email);
                }
            }
        });
    }

    //修改密码
    private void revise(String password, String email, String code) {
        String userDTO = gson.toJson(new UserCodeDTO(new User(email,password),code));
        updatePasswordServerPath = getApplicationContext().getString(R.string.updatePasswordServerPath);
//        System.out.println(updatePasswordServerPath);
        //创建请求体
        RequestBody requestBody = RequestBody.create(
                MediaType.parse("application/json"),//转换为json
                userDTO
        );
        //创建请求对象
        Request request = new Request.Builder()
                .post(requestBody)//post请求
                .header("Cookie",cookie)//cookie
                .url(updatePasswordServerPath)//url
                .build();
        Call call = okHttpClient.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //执行请求
                    response = call.execute();
                    responseContent = response.body().string();//响应内容
                    result = gson.fromJson(responseContent, Result.class);
                    if(result.getCode().equals("200")){
                        Toast.makeText(ForgetActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                    }else
                        Toast.makeText(ForgetActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
                }catch (Exception e){
                    System.out.println(e.getMessage());
                    Toast.makeText(ForgetActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        }).start();
    }

    //发送验证码
    private void sendVerificationCode(String email) {
        getCodeForUpdatePasswordServerPath = getApplicationContext().getString(R.string.getCodeForUpdatePasswordServerPath);
        String url = getCodeForUpdatePasswordServerPath + "?email=" + email;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        //创建新线程执行网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {//获取响应头中的Cookie并解析
                    response = okHttpClient.newCall(request).execute();//执行请求
                    cookie = response.header("Set-Cookie");
                    responseContent = response.body().string();//打印
                    result = gson.fromJson(responseContent, Result.class);//解析响应内容
                    if (result.getCode().equals("200")) {
                        runOnUiThread(() -> Toast.makeText(ForgetActivity.this, "验证码发送成功", Toast.LENGTH_SHORT).show());
                    } else {
                        runOnUiThread(() -> Toast.makeText(ForgetActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show());
                    }
                } catch (Exception e) {
                    runOnUiThread(() -> Toast.makeText(ForgetActivity.this, "与服务器连接失败", Toast.LENGTH_SHORT).show());
                }
            }
        }).start();
    }

    //倒计时
    private void countCode(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CountDownTimer countDownTimer = new CountDownTimer(60000, 1000) {
                    @Override
                    public void onTick(long l) {
                        forget_btn_verify.setEnabled(false);
                        forget_btn_verify.setText(l/1000 + "秒后重发");
                    }
                    @Override
                    public void onFinish() {
                        forget_btn_verify.setEnabled(true);
                        forget_btn_verify.setText("获取验证码");
                    }
                };
                countDownTimer.start();
            }
        });
    }
}

